$(function () {
  initArtCateList();
  const { form } = layui;
  const layer = layui.layer;
  function initArtCateList() {
    $.ajax({
      method: "GET",
      url: "/my/article/cates",
      success: function (res) {
        // console.log(res);
        const htmlStr = template("tpl-table", res);
        $("tbody").html(htmlStr);
      },
    });
  }
  let addcates = null;
  $("#btnAddCate").on("click", function () {
    addcates = layer.open({
      type: 1,
      area: ["500px", "250px"],
      title: "添加文章分类",
      content: $("#dialog-add").html(),
    });
  });
  $("body").on("submit", "#form-add", function (e) {
    e.preventDefault();
    $.ajax({
      url: "/my/article/addcates",
      method: "POST",
      data: $(this).serialize(),
      success: function (res) {
        if (res.status !== 0) {
          return layer.msg("提交失败");
        }
        initArtCateList();
        layer.msg("提交成功");
        layer.close(addcates);
      },
    });
  });
  var indexEdit = null;
  $("tbody").on("click", ".btn-edit", function () {
    // 弹出一个修改文章分类信息的层
    indexEdit = layer.open({
      type: 1,
      area: ["500px", "250px"],
      title: "修改文章分类",
      content: $("#dialog-edit").html(),
    });
    console.log($(this).attr("data-id"));
    var id = $(this).attr("data-id");
    $.ajax({
      method: "GET",
      url: "/my/article/cates/" + id,
      success: function (res) {
        form.val("form-edit", res.data);
      },
    });
  });

  $("body").on("submit", "#form-edit", function (e) {
    e.preventDefault();
    $.ajax({
      method: "POST",
      url: "/my/article/updatecate",
      data: $(this).serialize(),
      success: function (res) {
        if (res.status !== 0) {
          return layer.msg("更新数据失败");
        }
        layer.msg("更新数据成功");
        layer.close(indexEdit);
        initArtCateList();
      },
    });
  });

  $("body").on("click",'.layui-btn-xs', function () {
      console.log(1);
    var id = $(this).attr("data-id");
    layer.confirm("确认删除?", { icon: 3, title: "提示" }, function (index) {
        $.ajax({
            url:'/my/article/deletecate'+id,
            method:'GET',
            success: function (res){
                if (res.status !== 0) {layer.msg('删除失败')}
                layer.msg('删除分类成功！')
          layer.close(index)
          initArtCateList()
            }
        })
    });
  });
});
